<template>
  <div class="gene-map">
    <!-- 图例 -->
    <div class="legend">
      <div v-for="(color, type) in typeColors" :key="type" 
           class="legend-item" 
           @click="toggleVisibility(type)"
           :class="{ 'legend-item-hidden': !visibleTypes[type] }"
           style="cursor: pointer;">
        <span class="legend-color" :style="{ 
          backgroundColor: type === 'anchor' ? color : 'transparent', 
          borderLeft: type !== 'anchor' ? `4px solid ${color}` : 'none',
          width: type === 'anchor' ? '24px' : '4px',
          opacity: visibleTypes[type] ? 1 : 0.3
        }">
        </span>
        <span class="legend-label">{{ type.toUpperCase() }}</span>
      </div>
    </div>

    <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
      <!-- 染色体主体 -->
      <rect x="50" y="100" width="700" height="30" fill="#FFFFFF" stroke="#333" stroke-width="1"/>
      
      <!-- 所有可视化元素的容器 -->
      <g class="visualization-layer">
        <!-- Anchor节点 -->
        <template v-for="(item, index) in processedData.filter(i => i.type === 'anchor' && visibleTypes['anchor'])" :key="`anchor-${index}`">
          <g class="gene-marker">
            <rect
              :x="item.position - 5"
              y="90"
              width="10"
              height="50"
              :fill="typeColors[item.type]"
            />
          </g>
        </template>

        <!-- 连接线 - 只在anchor可见时显示 -->
        <template v-if="visibleTypes['anchor']" v-for="(connection, index) in connections" :key="index">
          <path
            :d="connection.path"
            fill="none"
            stroke="#666"
            stroke-width="1.5"
            opacity="0.7"
          />
        </template>

        <!-- Gene节点 -->
        <template v-for="(item, index) in processedData.filter(i => i.type === 'gene' && visibleTypes['gene'])" :key="`gene-${index}`">
          <g
            @mouseenter="showTooltip(item, $event)"
            @mouseleave="hideTooltip"
            class="gene-marker"
          >
            <line
              :x1="item.position"
              :y1="95"
              :x2="item.position"
              :y2="135"
              :stroke="typeColors[item.type]"
              stroke-width="2"
            />
            <rect
              :x="item.position - 5"
              y="90"
              width="10"
              height="50"
              fill="transparent"
              style="cursor: pointer"
            />
          </g>
        </template>

        <!-- CpG节点 -->
        <template v-for="(item, index) in processedData.filter(i => i.type === 'cpg' && visibleTypes['cpg'])" :key="`cpg-${index}`">
          <g
            @mouseenter="showTooltip(item, $event)"
            @mouseleave="hideTooltip"
            class="gene-marker"
          >
            <line
              :x1="item.position"
              :y1="95"
              :x2="item.position"
              :y2="135"
              :stroke="typeColors[item.type]"
              stroke-width="2"
            />
            <rect
              :x="item.position - 5"
              y="90"
              width="10"
              height="50"
              fill="transparent"
              style="cursor: pointer"
            />
          </g>
        </template>

        <!-- SNV节点 -->
        <template v-for="(item, index) in processedData.filter(i => i.type === 'snv' && visibleTypes['snv'])" :key="`snv-${index}`">
          <g
            @mouseenter="showTooltip(item, $event)"
            @mouseleave="hideTooltip"
            class="gene-marker"
          >
            <line
              :x1="item.position"
              :y1="95"
              :x2="item.position"
              :y2="135"
              :stroke="typeColors[item.type]"
              stroke-width="2"
            />
            <rect
              :x="item.position - 5"
              y="90"
              width="10"
              height="50"
              fill="transparent"
              style="cursor: pointer"
            />
          </g>
        </template>
      </g>

      <!-- 交互层 (最上层) -->
      <g class="interaction-layer">
        <!-- Anchor交互区域 -->
        <template v-for="(item, index) in processedData.filter(i => i.type === 'anchor')" :key="`anchor-interact-${index}`">
          <rect
            :x="item.position - 5"
            y="90"
            width="10"
            height="50"
            fill="transparent"
            style="cursor: pointer"
            @mouseenter="showTooltip(item, $event)"
            @mouseleave="hideTooltip"
          />
        </template>

        <!-- 其他类型的交互区域 -->
        <template v-for="(item, index) in processedData.filter(i => i.type !== 'anchor')" :key="`${item.type}-interact-${index}`">
          <rect
            :x="item.position - 5"
            y="90"
            width="10"
            height="50"
            fill="transparent"
            style="cursor: pointer"
            @mouseenter="showTooltip(item, $event)"
            @mouseleave="hideTooltip"
          />
        </template>
      </g>
      
      <!-- 刻度尺 -->
      <line x1="50" y1="140" x2="750" y2="140" stroke="#666" stroke-width="1"/>
      <template v-for="(tick, index) in ticks" :key="index">
        <line
          :x1="tick.x"
          y1="140"
          :x2="tick.x"
          y2="145"
          stroke="#666"
          stroke-width="1"
        />
        <text
          :x="tick.x"
          y="160"
          text-anchor="middle"
          font-size="10"
        >
          {{ tick.label }}
        </text>
      </template>
    </svg>

    <!-- Tooltip -->
    <div
      v-if="tooltip.show"
      class="tooltip"
      :style="{
        left: tooltip.x + 'px',
        top: `${tooltip.y - 80}px`
      }"
    >
      <div class="tooltip-content">
        <div><strong>Type:</strong> {{ tooltip.item?.type }}</div>
        <div><strong>Name:</strong> {{ tooltip.item?.name }}</div>
        <div><strong>Start:</strong> {{ tooltip.item?.start }}</div>
        <div><strong>End:</strong> {{ tooltip.item?.end }}</div>
        <div><strong>Sample ID:</strong> {{ tooltip.item?.sampleId }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import analysisDataSource from "@/assets/analysis2_plot.json";

const analysisData = analysisDataSource;
// 数据处理函数
const processAnalysisData = (data) => {
  const processed = [];
  const seen = new Set();

  data.forEach(item => {
    // 处理基因
    const geneKey = `gene-${item.gene}-${item.geneStart}-${item.geneEnd}`;
    if (!seen.has(geneKey)) {
      processed.push({
        name: item.gene,
        type: 'gene',
        start: item.geneStart,
        end: item.geneEnd,
        chr: item.chr,
        sampleId: item.sampleId
      });
      seen.add(geneKey);
    }

    // 处理SNV
    const snvKey = `snv-${item.snv}-${item.snvPos}`;
    if (!seen.has(snvKey)) {
      processed.push({
        name: item.snv,
        type: 'snv',
        start: item.snvPos,
        end: item.snvPos,
        chr: item.chr,
        sampleId: item.sampleId
      });
      seen.add(snvKey);
    }

    // 处理CpG
    const cpgKey = `cpg-${item.cpgPos}`;
    if (!seen.has(cpgKey)) {
      processed.push({
        name: item.cpgPos,
        type: 'cpg',
        start: item.cpgPos,
        end: item.cpgPos,
        chr: item.chr,
        sampleId: item.sampleId
      });
      seen.add(cpgKey);
    }

    // 处理锚点
    const anchor1Key = `anchor1-${item.anchor1Start}`;
    if (!seen.has(anchor1Key)) {
      const [start, end] = item.anchor1Start.split('-');
      processed.push({
        name: 'anchor1',
        type: 'anchor',
        start,
        end: end || start,
        chr: item.chr,
        sampleId: item.sampleId
      });
      seen.add(anchor1Key);
    }

    const anchor2Key = `anchor2-${item.anchor2Start}`;
    if (!seen.has(anchor2Key)) {
      const [start, end] = item.anchor2Start.split('-');
      processed.push({
        name: 'anchor2',
        type: 'anchor',
        start,
        end: end || start,
        chr: item.chr,
        sampleId: item.sampleId
      });
      seen.add(anchor2Key);
    }
  });

  return processed;
};
console.log(processAnalysisData(analysisData));
// 类型颜色映射
const typeColors = {
  gene: '#E41A1C',    // 鲜艳的红色，用于基因
  snv: '#377EB8',     // 明亮的蓝色，用于SNV
  cpg: '#4DAF4A',     // 鲜艳的绿色，用于CpG位点
  anchor: 'rgba(152, 78, 163, 0.3)'   // 浅紫色，用于锚点
};

// 处理数据
const processedData = computed(() => {
  const data = processAnalysisData(analysisData);
  const minPosition = Math.min(...data.map(item => parseInt(item.start)));
  const maxPosition = Math.max(...data.map(item => parseInt(item.end)));
  const scale = 700 / (maxPosition - minPosition);
  
  return data.map(item => ({
    ...item,
    position: 50 + (parseInt(item.start) - minPosition) * scale
  }));
});
console.log(processedData.value);
// 计算连接线
const connections = computed(() => {
  const result = [];
  const groupedData = {};
  
  // 按sampleId分组
  processedData.value.forEach(item => {
    if (item.type === 'anchor' && item.name) {
      if (!groupedData[item.sampleId]) {
        groupedData[item.sampleId] = {};
      }
      // 分别存储anchor1和anchor2
      if (item.name === 'anchor1') {
        groupedData[item.sampleId].anchor1 = item;
      } else if (item.name === 'anchor2') {
        groupedData[item.sampleId].anchor2 = item;
      }
    }
  });

  // 生成连接路径 - 修改为顶部连线
  Object.values(groupedData).forEach(anchors => {
    if (anchors.anchor1 && anchors.anchor2) {
      const { anchor1, anchor2 } = anchors;
      // 修改路径，使连线在顶部
      const path = `M ${anchor1.position} 90 Q ${(anchor1.position + anchor2.position) / 2} 45, ${anchor2.position} 90`;
      result.push({ path });
    }
  });

  return result;
});

// Tooltip状态
const tooltip = ref({
  show: false,
  x: 0,
  y: 0,
  item: null
});

// 显示tooltip
const showTooltip = (item, event) => {
  const rect = event.target.getBoundingClientRect();
  
  tooltip.value = {
    show: true,
    x: rect.left + (rect.width / 2),
    y: rect.top - 45,
    item
  };
};

// 隐藏tooltip
const hideTooltip = () => {
  tooltip.value.show = false;
};

// 生成刻度
const ticks = computed(() => {
  const data = processedData.value;
  const minPosition = Math.min(...data.map(item => parseInt(item.start)));
  const maxPosition = Math.max(...data.map(item => parseInt(item.end)));
  const tickCount = 5;
  const interval = (maxPosition - minPosition) / (tickCount - 1);
  
  return Array.from({ length: tickCount }, (_, i) => ({
    x: 50 + (i * 700 / (tickCount - 1)),
    label: Math.round(minPosition + i * interval).toLocaleString()
  }));
});

// 添加显示状态控制
const visibleTypes = ref({
  gene: true,
  snv: true,
  cpg: true,
  anchor: true
});

// 切换显示状态
const toggleVisibility = (type) => {
  visibleTypes.value[type] = !visibleTypes.value[type];
};
</script>

<style scoped>
.gene-map {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 20px;
}

.gene-map svg {
  width: 800px;
  height: 200px;
  transform: scale(1.5);
  background-color: #FFFFFF;
}

.gene-marker {
  transition: all 0.3s;
}

.gene-marker:hover {
  opacity: 0.8;
  filter: brightness(1.2);
}

.tooltip {
  position: fixed;
  z-index: 1000;
  pointer-events: none;
  transform: translateX(-50%);
}

.tooltip-content {
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  min-width: 150px;
}

.tooltip-content::after {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid rgba(0, 0, 0, 0.8);
}

.tooltip-content div {
  margin: 4px 0;
  line-height: 1.4;
}

text {
  font-family: Arial, sans-serif;
  dominant-baseline: middle;
}

.legend {
  display: flex;
  gap: 25px;
  padding: 15px;
  background: #ffffff;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  margin-bottom: -20px;
  z-index: 100;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 80px;
  padding: 5px 10px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.legend-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.legend-item-hidden {
  opacity: 0.5;
}

.legend-color {
  height: 24px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  display: inline-block;
}

.legend-label {
  font-size: 13px;
  color: #444;
  font-weight: 500;
  white-space: nowrap;
}
</style>